﻿using System; 
using System.Text;
using System.Collections.Generic; 
using System.Data;
using System.Data.SqlClient;
using ART.Data;
using ART.Common;
using ART.Model;
using ART.Cache;

namespace ART.BLL {
  //dictionary
 	public partial class B_dictionary
	{
   		
		public B_dictionary()
		{}
        #region __________基础方法__________
		/// <summary>
		/// 删除指定缓存
		/// </summary>
		public void ClearCache(string key)
		{
		    string CacheKey = "BLL/dictionary";
			if(!string.IsNullOrEmpty(key)){
			    CacheKey+="/"+key;
			}
			LRSCache.GetCacheService().RemoveObject(CacheKey);
		}
		/// <summary>
		/// 增加一条数据
		/// </summary>
        public bool Add(ART.Model.M_dictionary model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into dictionary(");			
            strSql.Append("Id,DictionaryName,ParentId,Sort,MainDictionaryId,IfDelete,ColPath");
			strSql.Append(") values (");
            strSql.Append("@Id,@DictionaryName,@ParentId,@Sort,@MainDictionaryId,@IfDelete,@ColPath");            
            strSql.Append(") ");            
            	
			#region __________参数__________	
			SqlParameter[] parameters = {
			            new SqlParameter("@Id", SqlDbType.Int,4) ,            
                        new SqlParameter("@DictionaryName", SqlDbType.VarChar,20) ,            
                        new SqlParameter("@ParentId", SqlDbType.Int,4) ,            
                        new SqlParameter("@Sort", SqlDbType.Int,4) ,            
                        new SqlParameter("@MainDictionaryId", SqlDbType.Int,4) ,            
                        new SqlParameter("@IfDelete", SqlDbType.Int,4) ,            
                        new SqlParameter("@ColPath", SqlDbType.NVarChar,500)             
              
            };
			
			            
            parameters[0].Value = model.Id;                        
            parameters[1].Value = model.DictionaryName;                        
            parameters[2].Value = model.ParentId;                        
            parameters[3].Value = model.Sort;                        
            parameters[4].Value = model.MainDictionaryId;                        
            parameters[5].Value = model.IfDelete;
            parameters[6].Value = getColPath(model.ParentId) + model.Id + ",";           			
            #endregion
            int i = SqlHelper.ExecNonQuery(strSql.ToString(), parameters);
            return i>0;		
		}

		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(ART.Model.M_dictionary model)
		{
		    StringBuilder strSql=new StringBuilder();
			#region __________语句__________
			strSql.Append("update dictionary set ");
			                        
            strSql.Append(" Id = @Id , ");                                    
            strSql.Append(" DictionaryName = @DictionaryName , ");                                    
            strSql.Append(" ParentId = @ParentId , ");                                    
            strSql.Append(" Sort = @Sort , ");                                    
            strSql.Append(" MainDictionaryId = @MainDictionaryId , ");                                    
            strSql.Append(" IfDelete = @IfDelete , ");                                    
            strSql.Append(" ColPath = @ColPath  ");            			
			strSql.Append(" where Id=@Id  ");
			
			#endregion	
			
			#region __________参数__________	
            SqlParameter[] parameters = {
			            new SqlParameter("@Id", SqlDbType.Int,4) ,            
                        new SqlParameter("@DictionaryName", SqlDbType.VarChar,20) ,            
                        new SqlParameter("@ParentId", SqlDbType.Int,4) ,            
                        new SqlParameter("@Sort", SqlDbType.Int,4) ,            
                        new SqlParameter("@MainDictionaryId", SqlDbType.Int,4) ,            
                        new SqlParameter("@IfDelete", SqlDbType.Int,4) ,            
                        new SqlParameter("@ColPath", SqlDbType.NVarChar,500)             
              
            };
            			            
            parameters[0].Value = model.Id;                        
            parameters[1].Value = model.DictionaryName;                        
            parameters[2].Value = model.ParentId;                        
            parameters[3].Value = model.Sort;                        
            parameters[4].Value = model.MainDictionaryId;                        
            parameters[5].Value = model.IfDelete;
            parameters[6].Value = getColPath(model.ParentId) + model.Id + ",";          			
            #endregion
			
            int rows=SqlHelper.ExecNonQuery(strSql.ToString(),parameters);
			if (rows > 0)
			{
			//string cachekey="info_"+Id;
			//ClearCache(cachekey);
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(int Id)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from dictionary ");
			strSql.Append(" where Id=@Id ");
						SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.Int,4)			};
			parameters[0].Value = Id;

			int rows=SqlHelper.ExecNonQuery(strSql.ToString(),parameters);
			
			//string cachekey="info_"+Id;
			//ClearCache(cachekey);
			
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

 	    /// <summary>
 	    /// 得到一个对象实体
 	    /// </summary>
 	    public ART.Model.M_dictionary GetModel(int Id)
 	    {
 	        string CacheKey = "BLL/dictionary/info_" + Id;
 	        object objModel = LRSCache.GetCacheService().RetrieveObject(CacheKey);
 	        if (objModel == null)
 	        {
 	            StringBuilder strSql = new StringBuilder();
 	            strSql.Append("select * from dictionary ");
 	            strSql.Append(" where Id=@Id ");

 	            SqlParameter[] parameters =
 	                {
 	                    new SqlParameter("@Id", SqlDbType.Int, 4)
 	                };
 	            parameters[0].Value = Id;


 	            ART.Model.M_dictionary model = new ART.Model.M_dictionary();
 	            DataSet ds = SqlHelper.ExecDataSet(strSql.ToString(), parameters);

 	            if (ds.Tables[0].Rows.Count > 0)
 	            {
 	                #region __________实体赋值__________

 	                if (ds.Tables[0].Rows[0]["Id"].ToString() != "")
 	                {
 	                    model.Id = int.Parse(ds.Tables[0].Rows[0]["Id"].ToString());
 	                }
 	                model.DictionaryName = ds.Tables[0].Rows[0]["DictionaryName"].ToString();
 	                if (ds.Tables[0].Rows[0]["ParentId"].ToString() != "")
 	                {
 	                    model.ParentId = int.Parse(ds.Tables[0].Rows[0]["ParentId"].ToString());
 	                }
 	                if (ds.Tables[0].Rows[0]["Sort"].ToString() != "")
 	                {
 	                    model.Sort = int.Parse(ds.Tables[0].Rows[0]["Sort"].ToString());
 	                }
 	                if (ds.Tables[0].Rows[0]["MainDictionaryId"].ToString() != "")
 	                {
 	                    model.MainDictionaryId = int.Parse(ds.Tables[0].Rows[0]["MainDictionaryId"].ToString());
 	                }
 	                if (ds.Tables[0].Rows[0]["IfDelete"].ToString() != "")
 	                {
 	                    model.IfDelete = int.Parse(ds.Tables[0].Rows[0]["IfDelete"].ToString());
 	                }
 	                model.ColPath = ds.Tables[0].Rows[0]["ColPath"].ToString();


 	                #endregion

 	                LRSCache.GetCacheService().AddObject(CacheKey, model, 2*60*60);
 	                return model;
 	            }
 	            else
 	            {
 	                return null;
 	            }

 	        }
 	        return (ART.Model.M_dictionary) objModel;
 	    }

 	    /// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			return GetList(0,strWhere,"");
		}
		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			return GetList(0,"*",strWhere,filedOrder);
		}
		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string FieldName,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" "+FieldName+" FROM dictionary ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			if(filedOrder.Trim()!="")
			{
				strSql.Append(" order by " + filedOrder);
			}
			return SqlHelper.ExecDataSet(strSql.ToString());
		}
#endregion

      #region __________自定义方法__________
        private string getColPath(int pareid)
        {
            string tmp = "";
            M_dictionary di = GetModel(pareid);
            if (di != null && di.ParentId != 0)
            {
                tmp = "," + getColPath(di.ParentId) + "," + pareid + ",";
            }
            else
            {
                tmp = "," + pareid + ",";
            }
            tmp = tmp.Replace(",,", ",");
            if (!tmp.StartsWith(",0,"))
            {
                tmp = ",0," + tmp;
            }
            return tmp.Replace(",,", ",");
        }
        public int GetMaxId()
        {
            string cmdText = "select max(id) from dictionary ";
            object obj = SqlHelper.ExecScalar(cmdText, new SqlParameter[0]);
            if (obj == DBNull.Value || obj == null)
            {
                return 1;
            }
            else
            {

                return Convert.ToInt32(obj) + 1;

            }
        }
        /// <summary>
        /// 获取字符名
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isinparent"></param>
        /// <returns></returns>
        public string GetString(int id, bool isinparent)
        {
            string tmp = "";
            M_dictionary di = GetModel(id);
            if (di != null)
            {
                if (di.ParentId != 0 && isinparent)
                {
                    tmp = GetString(di.ParentId, isinparent) + "-" + di.DictionaryName;
                }
                else
                {
                    tmp = di.DictionaryName;
                }
            }

            return tmp;
        }
        /// <summary>
        /// 获取指定父级下所有

        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public DataTable GetListByParent(int pid)
        {
            string CacheKey = "BLL/dictionary/datatable/_" + pid;
            object objdt = LRSCache.GetCacheService().RetrieveObject(CacheKey);
            if (objdt == null)
            {
                DataTable dt = GetList(" CHARINDEX('," + pid + ",',colpath)>0 ").Tables[0];
                if (dt != null)
                {
                    LRSCache.GetCacheService().AddObject(CacheKey, dt, 5 * 60 * 60);
                    return dt;
                }
                return null;
            }
            else
            {
                return (DataTable)objdt;
            }
        }
        /// <summary>
        /// 获取指定父级下所有ID
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public string GetIDbyParent(int pid, bool includePid)
        {
            string tmp = "0";
            DataTable dt = GetListByParent(pid);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["id"].ToString() == pid.ToString() && !includePid)
                    {
                        continue;
                    }
                    tmp += "," + dr["id"].ToString();
                }
            }
            tmp = tmp.Replace(",,", ",").Trim(',');
            return tmp;
        }

        public string GetString(string ids)
        {
            string rev = "";
            DataSet ds = GetList(0, "dictionaryName", " id in(" + ids.Trim(',') + ") ", "");
            if (ds.Tables[0] != null)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    rev += dr[0] + ",";
                }
            }
            return rev.Trim(',');
        }
      #endregion 
	}
}

